package easytasks.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import easytasks.data.DataManager;
import easytasks.data.DataSetup;
import easytasks.data.TaskCategory;
import easytasks.main.R;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class EditTaskCategoriesActivity extends ListActivity 
{
	private ArrayList<TaskCategory> categories;
	private List<TaskCategory> selectedCategories;
	
	private DataSetup dataInit;
	private DataManager dataManager;
	
	private ListView listTaskCategories;
	private EditText editAddCategory;
	private ImageButton butAddCategory;
	private CheckBox[] rowCheckboxes = null;	
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edittaskcategories);
        
        listTaskCategories = getListView();
        registerForContextMenu(listTaskCategories);

        editAddCategory = (EditText)findViewById(R.id.editEditTaskCategoriesAdd);
        editAddCategory.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s)
			{
				checkRequiredData();
			}
		});
        
        butAddCategory = (ImageButton)findViewById(R.id.butEditTaskCategoriesAdd);
        butAddCategory.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
				TaskCategory newCategory = new TaskCategory(editAddCategory.getText().toString().trim());
					
				if (categories.contains(newCategory))
				{
					Toast.makeText(EditTaskCategoriesActivity.this, R.string.edittaskcategories_edit_alreadyexists, Toast.LENGTH_LONG).show();
				}
				else
				{
					dataManager.addTaskCategory(newCategory);
					selectedCategories.add(newCategory);
					refresh();
				}
			}
        });
        
        ((Button)findViewById(R.id.butEditTaskCategoriesOk)).setOnClickListener(new OnClickListener() {
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.putExtra("categories", (Serializable) selectedCategories);				
				setResult(EditTaskActivity.SUBACTIVITY_RESULT_CATEGORIES_OK_CODE, intent);
				finish();
			}
		});
        
        ((Button)findViewById(R.id.butEditTaskCategoriesCancel)).setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
				finish();
			}
		});
        
        setResult(EditTaskActivity.SUBACTIVITY_RESULT_CANCEL_CODE);
        loadInputCategories();
        
        checkRequiredData();
        
        dataInit = new DataSetup(this);
        dataManager = new DataManager(dataInit, PreferenceManager.getDefaultSharedPreferences(this));
    }
	
	private void checkRequiredData() 
	{
		butAddCategory.setEnabled(!editAddCategory.getText().toString().trim().equals(""));
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		if (v == listTaskCategories)
		{
			AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
			menu.setHeaderTitle(categories.get(info.position).getName());
			String[] menuItems = getResources().getStringArray(R.array.managetaskcategories_contextmenu);
			for (int i = 0; i < menuItems.length; i++) menu.add(Menu.NONE, i, i, menuItems[i]);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		final TaskCategory oldCategory = categories.get(info.position);
		
		switch(item.getItemId())
		{
			case 0:
				final NewTaskCategoryNameDialog dialogNewCategory = new NewTaskCategoryNameDialog(this, oldCategory);
				dialogNewCategory.setOnOkClickHandler(new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) 
					{
						TaskCategory newCategory = dialogNewCategory.getNewValue();
						
						if (oldCategory.equals(newCategory)) 
						{
							Toast.makeText(EditTaskCategoriesActivity.this, R.string.edittaskcategories_edit_equals, Toast.LENGTH_LONG).show();
						}
						else if (categories.contains(newCategory))
						{
							Toast.makeText(EditTaskCategoriesActivity.this, R.string.edittaskcategories_edit_alreadyexists, Toast.LENGTH_LONG).show();
						}
						else
						{
							dataManager.updateTaskCategory(oldCategory, newCategory);
							
							if (selectedCategories.contains(oldCategory)) 
							{
								selectedCategories.set(selectedCategories.indexOf(oldCategory), newCategory);
							}
							
							refresh();
						}
					}
				});
				
				dialogNewCategory.show();
				break;
			case 1:
				dataManager.removeTaskCategory(oldCategory);
				refresh();
				break;
		}
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private void loadInputCategories() 
	{
		Serializable inputCategories = getIntent().getSerializableExtra("categories");
		if (inputCategories == null) throw new IllegalArgumentException("Categories to edit not defined");
		
		selectedCategories = (List<TaskCategory>) inputCategories;
	}
	
	@Override
    public void onResume()
    {
    	super.onResume();
    	refresh();
    }
	
	private void refresh() 
    {
		categories = new ArrayList<TaskCategory>(dataManager.getAllTaskCategories());
		
		for (TaskCategory selectedCategory : selectedCategories)
		{
			if (!categories.contains(selectedCategory)) selectedCategories.remove(selectedCategory);
		}
		
		rowCheckboxes = new CheckBox[categories.size()];
		setListAdapter(new TaskCategoryAdapter(this, R.layout.edittaskcategoriesrow, categories));
		editAddCategory.setText("");
    }
	
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
    	rowCheckboxes[position].toggle();
    }
	
	private class TaskCategoryAdapter extends ArrayAdapter<TaskCategory>
    {
    	private ArrayList<TaskCategory> categories;
    	
    	public TaskCategoryAdapter(Context context, int textViewResourceId, ArrayList<TaskCategory> objects)
    	{
    		super(context, textViewResourceId, objects);
    		this.categories = objects;
    	}

    	public View getView(final int position, View convertView, ViewGroup parent)
    	{
    		LayoutInflater inflater = getLayoutInflater();
    		final View row = inflater.inflate(R.layout.edittaskcategoriesrow, parent, false);
    		
    		TaskCategory entry = categories.get(position);
    		
    		TextView textName = (TextView) row.findViewById(R.id.textEditTaskCategoriesRowName);
    		textName.setText(entry.getName());
    		
    		CheckBox checkSelected = (CheckBox) row.findViewById(R.id.checkEditTaskCategoriesRowSelected);
    		checkSelected.setChecked(EditTaskCategoriesActivity.this.selectedCategories.contains(entry));
    		rowCheckboxes[position] = checkSelected;
    		
    		checkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
				{
					TaskCategory category = EditTaskCategoriesActivity.this.categories.get(position);
					
					if (isChecked && !EditTaskCategoriesActivity.this.selectedCategories.contains(category))
					{
						EditTaskCategoriesActivity.this.selectedCategories.add(category);
					}
					else if (EditTaskCategoriesActivity.this.selectedCategories.contains(category))
					{
						EditTaskCategoriesActivity.this.selectedCategories.remove(category);
					}
				}
			});
    		
    		return row;
    	}
    }
}
